package com.herench.bs.agent.impl;

import com.herench.bs.agent.BillInHosAgent;
import com.herench.bs.dao.IUserDao;
import com.herench.bs.support.WsClientFactory;
import com.herench.bs.transfer.Dialect;
import com.herench.bs.utils.DataFormatUtils;
import com.herench.bs.utils.IdGenerator;
import org.apache.cxf.endpoint.Client;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class BillInHosAgentImpl implements BillInHosAgent {
    @Autowired
    private IUserDao userDao;

    @Value("${his_ws_url}")
    private String hisWsUrl;
    private static final Logger logger = Logger.getLogger(BillInHosAgentImpl.class);

    @Override
    public Map<String, Object> getPat(Map<String, Object> params) throws Exception {
        Document tplDoc = getTplDoc("GetPatInHos");
        Element dataRowElement = tplDoc.getRootElement().element("CommitData").addElement("Data");
//        Map<String, Object> user = userDao.findName((String) params.get("phone"));
        String idNo = (String) params.get("idNo");
        Element dataRowOrder = dataRowElement.addElement("DataRow");
        dataRowOrder.addAttribute("ID_NO", idNo);
        String data = tplDoc.asXML();
        Client client = WsClientFactory.getInstance().getWsClient(hisWsUrl);
        Object[] results = client.invoke("send", data);
        String originalResXmlMessage = (String) results[0];
        Map<String, Object> resMap = new HashMap<>(16);
        Document document = DocumentHelper.parseText(originalResXmlMessage);
        Element resultInfo = document.getRootElement().element("Result").element("Info");
        String executeStatus = resultInfo.attributeValue("EXECUTE_STATUS");
        String executeMessage = resultInfo.attributeValue("EXECUTE_MESSAGE");
        if (Dialect.getSuccessfulState().equals(executeStatus)) {
            Element dataRowPat = document.getRootElement().element("ReturnData").element("Data").element("DataRow");
            resMap.put("inPatientId", dataRowPat.attributeValue("IN_PATIENT_ID"));
            resMap.put("patientId", dataRowPat.attributeValue("PATIENT_ID"));
            resMap.put("name", dataRowPat.attributeValue("NAME"));
            resMap.put("sex", dataRowPat.attributeValue("SEX"));
            resMap.put("dateOfBirth", dataRowPat.attributeValue("DATE_OF_BIRTH"));
            resMap.put("idNo", dataRowPat.attributeValue("ID_NO"));
            resMap.put("mailingAddress", dataRowPat.attributeValue("MAILING_ADDRESS"));
            resMap.put("phoneNumberBusiness", dataRowPat.attributeValue("PHONE_NUMBER_BUSINESS"));
            resMap.put("nextOfKin", dataRowPat.attributeValue("NEXT_OF_KIN"));
            resMap.put("relationship", dataRowPat.attributeValue("REALATIONSHIP"));
            resMap.put("nextOfKinPhone", dataRowPat.attributeValue("NEXT_OF_KIN_PHONE"));
            resMap.put("admissionDateTime", dataRowPat.attributeValue("ADMISSION_DATE_TIME"));
            resMap.put("dischargeDateTiome", dataRowPat.attributeValue("DISCHARGE_DATE_TIME"));
            resMap.put("days", dataRowPat.attributeValue("DAYS"));
            resMap.put("deptAdmissionTo", dataRowPat.attributeValue("DEPT_ADMISSION_TO"));
            resMap.put("wardName", dataRowPat.attributeValue("WARD_NAME"));
            resMap.put("bedNo", dataRowPat.attributeValue("BED_NO"));
            resMap.put("attendingDoctor", dataRowPat.attributeValue("ATTENDING_DOCTOR"));
            resMap.put("nurseResponsibility", dataRowPat.attributeValue("NURSE_RESPONSIBILITY"));
            resMap.put("totalcharges", dataRowPat.attributeValue("TOTALCHARGES"));
            resMap.put("totalprepay", dataRowPat.attributeValue("TOTALPREPAY"));
            resMap.put("unsettled", dataRowPat.attributeValue("UNSETTLED"));
            resMap.put("settled", dataRowPat.attributeValue("SETTLED"));
            resMap.put("balance", dataRowPat.attributeValue("BALANCE"));
            resMap.put("status", dataRowPat.attributeValue("STATUS"));
            Map<String, Object> map = getList(params);
            if (map.size() > 0) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("billList");
                resMap.put("bill", list);
                resMap.put("billamount", list.get(0).get("billamount"));
            }
        } else {
            resMap.put("code", executeStatus);
            resMap.put("message", executeMessage);
        }
        return resMap;
    }

    @Override
    public Map<String, Object> getList(Map<String, Object> params) throws Exception {
        Document tplDoc = getTplDoc("GetDailyBill");
        Element dataRowElement = tplDoc.getRootElement().element("CommitData").addElement("Data");
        Map<String, Object> user = userDao.findName((String) params.get("phone"));
        String idNo = (String) params.get("idNo");
        String billDate = (String) params.get("billDate");
        Element dataRowOrder = dataRowElement.addElement("DataRow");
        dataRowOrder.addAttribute("ID_NO", idNo);
        dataRowOrder.addAttribute("Bill_Date", billDate);
        String data = tplDoc.asXML();
        Client client = WsClientFactory.getInstance().getWsClient(hisWsUrl);
        Object[] results = client.invoke("send", data);
        String originalResXmlMessage = (String) results[0];
        Map<String, Object> res = new HashMap<>(16);
        Document document = DocumentHelper.parseText(originalResXmlMessage);
        Element resultInfo = document.getRootElement().element("Result").element("Info");
        String executeStatus = resultInfo.attributeValue("EXECUTE_STATUS");
        String executeMessage = resultInfo.attributeValue("EXECUTE_MESSAGE");
        List<Map<String, Object>> billList = new ArrayList<>();
        if (Dialect.getSuccessfulState().equals(executeStatus)) {
            List<Element> billDataRows = document.getRootElement().element("ReturnData").element("Data").elements();
            if (billDataRows != null && billDataRows.size() > 0) {
                for (Element dataRow : billDataRows) {
                    Map<String, Object> resMap = new HashMap<>(16);
                    resMap.put("itemClassCode", dataRow.attributeValue("ITEM_CLASS_CODE"));
                    resMap.put("itemClassName", dataRow.attributeValue("ITEM_CLASS_NAME"));
                    resMap.put("itemCharges", dataRow.attributeValue("ITEM_CHARGES"));
                    resMap.put("billamount", dataRow.attributeValue("BILLAMOUNT"));

                    String itemClassCode = (String) resMap.get("itemClassCode");
                    Document tplDoc1 = getTplDoc("GetDailyBillDetail");
                    Element dataRowElement1 = tplDoc1.getRootElement().element("CommitData").addElement("Data");
                    Element dataRowOrder1 = dataRowElement1.addElement("DataRow");
                    dataRowOrder1.addAttribute("ITEM_CLASS_CODE", itemClassCode);
                    dataRowOrder1.addAttribute("ID_NO", idNo);
                    dataRowOrder1.addAttribute("Bill_Date", billDate);
                    String data1 = tplDoc1.asXML();
                    Client client1 = WsClientFactory.getInstance().getWsClient(hisWsUrl);
                    Object[] results1 = client1.invoke("send", data1);
                    String originalResXmlMessage1 = (String) results1[0];
                    Document document1 = DocumentHelper.parseText(originalResXmlMessage1);
                    Element resultInfo1 = document1.getRootElement().element("Result").element("Info");
                    String executeStatus1 = resultInfo1.attributeValue("EXECUTE_STATUS");
                    String executeMessage1 = resultInfo1.attributeValue("EXECUTE_MESSAGE");
                    List<Map<String, Object>> billList1 = new ArrayList<>();
                    if (Dialect.getSuccessfulState().equals(executeStatus1)) {
                        List<Element> billDataRows1 = document1.getRootElement().element("ReturnData").element("Data").elements();
                        if (billDataRows1 != null && billDataRows1.size() > 0) {
                            for (Element dataRow1 : billDataRows1) {
                                Map<String, Object> resMap1 = new HashMap<>(16);
                                resMap1.put("detailId", dataRow1.attributeValue("DETAIL_ID"));
                                resMap1.put("detailName", dataRow1.attributeValue("DETAIL_NAME"));
                                resMap1.put("detailSpec", dataRow1.attributeValue("DETAIL_SPEC"));
                                resMap1.put("detailPrice", dataRow1.attributeValue("DETAIL_PRICE"));
                                resMap1.put("detailCount", dataRow1.attributeValue("DETAIL_COUNT"));
                                resMap1.put("detailUnit", dataRow1.attributeValue("DETAIL_UNIT"));
                                resMap1.put("detailAmount", dataRow1.attributeValue("DETAIL_AMOUNT"));
                                billList1.add(resMap1);
                            }
                            resMap.put("billDetail", billList1);
                        }
                    }

                    billList.add(resMap);
//
                }
                res.put("billList", billList);
            }
        }
//        else {
//                    res.put("code", executeStatus);
//                    res.put("message", executeMessage);
//                }
        return res;

    }


    public Document getTplDoc(String method) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("BITCRoot");
        root.addElement("CommitData");
        root.addElement("ReturnData");
        Element clientInfo = root.addElement("ClientInfo");
        Element clientInfoElement = clientInfo.addElement("Info");
        clientInfoElement.addAttribute("METHOD", method).addAttribute("OPT_ID", "1611").addAttribute("OPT_NAME", "微信公众").addAttribute("OPT_IP", "192.168.1.106").addAttribute("OPT_DATE", DataFormatUtils.getTimeString(new Date())).addAttribute("OPT_GUID", IdGenerator.getUUID().toLowerCase()).addAttribute("TOKEN", "").addAttribute("OPT_ACCT", "");
        Element serverInfo = root.addElement("ServerInfo");
        serverInfo.addAttribute("DEV_ID", "").addAttribute("DEV_IP", "").addAttribute("DEV_DATE", "").addAttribute("DEV_GUID", "").addAttribute("DEV_ACCT", "");
        Element resultInfoElement = root.addElement("Result").addElement("Info");
        resultInfoElement.addAttribute("EXECUTE_STATUS", "").addAttribute("EXECUTE_MESSAGE", "");
        return document;
    }
}
